import { DoubleLeftOutlined, DoubleRightOutlined, LeftOutlined, RightOutlined } from '@ant-design/icons';
import { Button } from 'antd';
import { useExtendRef } from '../../../../util';

const buttonStyle: any = { size: 'small', style: { display: 'block', width: 30, margin: 8 } };
/**
 * 穿梭按钮
 * @param props
 * @constructor
 */
export default function ShuttleButtons(props) {
  const {
    getRowKey,
    addResult: defaultAddResult,
    removeResult: defaultRemoveResult,
    getActiveTable,
    getResultTable,
    outRef,
    hasSelectAll = true,
    isHorizontal = false,
    rowDisable,
    subRowDisable
  } = props;

  const addResult =
    defaultAddResult ||
    ((values: any) => {
      const selected: any = [];
      const existValues = getResultTable()
        .getRows()
        .map((r) => getRowKey(r));
      values.forEach((value) => {
        if (existValues.indexOf(getRowKey(value)) === -1) {
          const newVal = JSON.parse(JSON.stringify(value));
          selected.push(newVal);
        }
      });
      getResultTable().addRows(selected);
    });
  const removeResult =
    defaultRemoveResult ||
    ((indexes?: number[] | number) => {
      if (indexes === undefined) {
        const initData = getResultTable()
          .getData()
          .filter((x) => subRowDisable(x));
        getResultTable().setDataSource(initData);
      } else {
        getResultTable().deleteRows(indexes);
      }
    });

  useExtendRef(outRef, {
    toLeft: removeResult,
    toRight: addResult
  });

  buttonStyle.style.transform = isHorizontal ? 'rotate(90deg)' : 'rotate(0deg)';
  return (
    <div
      style={{
        display: 'flex',
        alignItems: 'center',
        justifyContent: 'center',
        flexDirection: isHorizontal ? 'row' : 'column'
      }}
    >
      <Button {...buttonStyle} icon={<RightOutlined />} onClick={() => addResult(getActiveTable().getSelectedData())} />
      {hasSelectAll && (
        <Button
          {...buttonStyle}
          icon={<DoubleRightOutlined />}
          onClick={() =>
            addResult(
              getActiveTable()
                .getRows()
                .filter((x) => !rowDisable(x))
            )
          }
        />
      )}
      <Button
        {...buttonStyle}
        icon={<LeftOutlined />}
        onClick={() => removeResult(getResultTable().getSelectedIndexes())}
      />
      {hasSelectAll && <Button {...buttonStyle} icon={<DoubleLeftOutlined />} onClick={() => removeResult()} />}
    </div>
  );
}
